﻿using EasyDDD.AdminModule.Domain.AggregateSysAdminRole;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace EasyDDD.AdminModule.Application.CommandsSysAdminRole
{
    [AutoMapperTo(typeof(SysAdminRole))]
    public record SysAdminRoleUpdateCommand : ICommand<SysAdminRole>
    {
        public Guid Id { get; set; }
        public Guid RowVersion { get; set; } = default!;
        public string Code { get; set; } = default!;
        public string Name { get; set; } = default!;
        public string Remark { get; set; } = default!;
    }
    public class SysAdminRoleUpdateCommandValidator : AbstractValidator<SysAdminRoleUpdateCommand>
    {
        public SysAdminRoleUpdateCommandValidator(Repository.SysAdminRoleRepository repository)
        {
            var query = repository.AsQueryable();

            //RuleFor(x => x.Id).LessThanOrEqualTo(0)
            //    .WithErrorCode("错误的ID");
            RuleFor(x => x.Code).NotEmpty().MaximumLength(10)
                .WithMessage("权限标识不能为空");
            RuleFor(x => x.Name).NotEmpty().MaximumLength(10)
                .WithMessage("角色名称不能为空");

            RuleFor(x => x).Must(input => !query.Any(e => e.Id != input.Id && e.Code == input.Code))
                .WithMessage("权限标识不能重复");
            RuleFor(x => x).Must(input => !query.Any(e => e.Id != input.Id && e.Name == input.Name))
                .WithMessage("角色名称不能重复");
        }
    }
    public class SysAdminRoleUpdateCommandHandler(
       //IMapper mapper,
       Repository.SysAdminRoleRepository repository,
       ILogger<SysAdminRoleUpdateCommandHandler> logger)
       : ICommandHandler<SysAdminRoleUpdateCommand, SysAdminRole>
    {
        public async Task<SysAdminRole> Handle(SysAdminRoleUpdateCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysAdminRoleUpdateCommandHandler");
            var entity = await repository.GetAsync(request.Id, request.RowVersion);
            entity.Set(request.Name, request.Code, request.Remark);
            return entity;
        }
    }
}
